/**
 * 
 */
package com.sys.object.common.utils;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

/**
 * @author JDYG-001
 *
 */
public class FileSaveByHttpsUtils {
	
	CloseableHttpClient m_HttpClient;
	
	public FileSaveByHttpsUtils(){
		if(m_HttpClient==null)
			m_HttpClient = HttpClients.createDefault();
	}

	public byte[] postBytes(String serverUrl,byte[] data,String contentType) throws IOException{
		//http://control.iqudian.com/nktt/image/save.json
		HttpPost httpPost = new HttpPost(serverUrl);
		httpPost.setEntity(new ByteArrayEntity(data));
		if (contentType != null)
			httpPost.setHeader("Content-type", contentType);
		CloseableHttpResponse httpResponse = m_HttpClient.execute(httpPost);
		try {
			HttpEntity entityResponse = httpResponse.getEntity();
			int contentLength = (int) entityResponse.getContentLength();
			if (contentLength <= 0)
				throw new IOException("No response");
			byte[] respBuffer = new byte[contentLength];
			if (entityResponse.getContent().read(respBuffer) != respBuffer.length)
				throw new IOException("Read response buffer error");
			return respBuffer;
		} finally {
			httpResponse.close();
		}
	}
	
	public byte[] postBytesStream(String url, byte[] bytes) throws IOException {
		return postBytes(url, bytes, "application/octet-stream");
	}
	public String postBytesStreamToStr(String url, byte[] bytes) {
		try{
			byte[] data = postBytesStream(url, bytes);
			if(data!=null&&data.length>0){
				return new String(data);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
		
	}
	
	public byte[] postBytes(String url, byte[] bytes) throws IOException {
		return postBytes(url, bytes, null);
	}
}
